from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.utils.decorators import method_decorator
from django.views.generic import TemplateView,CreateView
from demoapp.models import Note
from django.contrib import admin
from django.urls import path, include, re_path


@method_decorator(login_required,name='post')
class NoteView(CreateView):
    success_url = '/'

    def get_form_class(self):
        class NoteForm(forms.ModelForm):
            content = forms.CharField(initial='今日分享\n', label='分享区域', help_text='必填，分享内容')

            class Meta:
                exclude = ['created_by']
                model = Note
        return NoteForm

    def get_context_data(self, **kwargs):
        context =  super().get_context_data(**kwargs)
        # 最近10次的内容
        result = []
        notes = Note.objects.all().order_by('-id')[:10]
        if notes:
            result = notes
        context['result'] = result
        return context

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super().form_valid(form)

from django.views.generic import DetailView
class NoteDetail(DetailView):
    queryset = Note.objects.all()

from django import forms
from demoapp.models import Imgs
class ImgForm(CreateView):
    queryset = Imgs.objects.all()

    def get_form_class(self):
        class ImgForm(forms.ModelForm):
            class Meta:
                model = Imgs
                fields = '__all__'
        return ImgForm

    def form_valid(self, form):
        form.save()
        return JsonResponse({
            "msg": "",
            "code": 0,
            "data": {
                "errFiles": [],
                "succMap": {
                    form.instance.img.name.rsplit('/')[-1]: f'media/{form.instance.img.name}',
                }
            }
        })

    def form_invalid(self, form):
        return JsonResponse({})



from django.views.static import serve
from django.contrib.auth.views import LoginView,LogoutView
urlpatterns = [
    path('admin/', admin.site.urls),

    re_path('^$',NoteView.as_view(template_name='demoapp/index.html'),name='index'),
    path('<int:pk>',NoteDetail.as_view(template_name='demoapp/detail.html'),name='detail'),
    path('accounts/login/',LoginView.as_view(template_name='login.html'),name='login'),
    path('accounts/logout/',LogoutView.as_view(),name='logout'),

    path('vditor/uploads/',login_required(ImgForm.as_view()),name='create_img'),
]
from django.conf.urls.static import static
if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
